<template>
  <div class="box">
    <header>
      <van-nav-bar title="购物车">
        <template #left>
          <van-icon
            name="arrow-left"
            size="26"
            color="black"
            @click="$router.back()"
          />
        </template>
        <template #right>
          <van-popover
            v-model="showPopover"
            trigger="click"
            :actions="actions"
            @select="onSelect"
            placement="bottom-end"
            theme="dark"
          >
            <template #reference>
              <van-icon name="ellipsis" size="26" color="black" />
            </template>
          </van-popover>
        </template>
      </van-nav-bar>
    </header>
    <main class="main" @scroll="scrollMe" ref="main">
      <!-- 未登录显示页面 -->
      <div class="notlogin" v-if="loginState">
        <!-- 顶部提示登录 -->
        <div class="cartlogin">
          <b>登录后可同步账户购物车中的商品</b>
          <van-button
            class="vbtn"
            round
            size="small"
            color="linear-gradient(to right, #ff6034, #ee0a24)"
            @click="$router.push('/login')"
            >登录</van-button
          >
        </div>
        <!-- 主题提示登录 -->
        <div class="carticon">
          <div>
            <van-icon name="cart-circle" size="100" color="red" />
            <p>登录后可同步购物车中的商品</p>
          </div>
          <img
            src="https://img12.360buyimg.com/img/s694x148_jfs/t1/171999/12/22113/58222/61bad82eE0dcf6d31/d92d1e829bf953da.png"
            alt=""
            width="100%"
          />
        </div>
      </div>
      <!-- 已登录显示页面 -->
      <div class="islogin" v-else>
        <!-- 购物车没有数据时显示 -->
        <div class="nothing" v-if="empty">
          <van-empty description="购物车空空如也,去逛逛吧~" />
          <img
            src="https://img12.360buyimg.com/img/s694x148_jfs/t1/171999/12/22113/58222/61bad82eE0dcf6d31/d92d1e829bf953da.png"
            alt=""
            width="100%"
          />
        </div>
        <!-- 购物车有数据时显示 -->
        <div class="hasthing" v-else>
          <!-- 购物车头部地址和编辑商品按钮 -->
          <div class="adress">
            <p   v-if="addressbtn" @click="$router.push('/my_address')"><van-icon name="location-o"/>{{deAddress}}</p>
            <p v-if="!addressbtn"></p>
            <span v-if="addressbtn" @click="addressbtn=!addressbtn">编辑商品</span>
            <span  v-if="!addressbtn" @click="addressbtn=!addressbtn">完成</span>
          </div>
          <!-- 购物车列表 -->
          <div>
            <van-swipe-cell v-for="(item, index) in cartList" :key="index" :name="item.cartid" :before-close="beforeClose">
            <van-checkbox
              v-model="item.flag"
              checked-color="#ee0a24"
              @change="changeSelector(item.cartid, item.flag)"
            ></van-checkbox>
            <van-card
              :price="item.originprice"
              :title="item.proname"
              :thumb="item.img1"
            >
              <template #num>
                <van-stepper
                  v-model="item.num"
                  theme="round"
                  button-size="22"
                  disable-input
                  @change="changeNum(item.cartid, item.num)"
                />
              </template>
            </van-card>
            <template #right>
              <van-button
                square
                text="删除"
                type="danger"
                class="delete-button"
              />
            </template>
          </van-swipe-cell>
          <!-- 商品结算 -->
          <van-submit-bar v-if="addressbtn" :disabled="checkednum==0?true:false" :price="price" @submit="onSubmit" :button-text="'提交订单('+checkednum+')'">
            <van-checkbox v-model="isAll">全选</van-checkbox>
            <template #tip>
              你的收货地址不支持同城送,
              <span>修改地址</span>
            </template>
          </van-submit-bar>
          <van-submit-bar v-if="!addressbtn">
            <van-checkbox v-model="isAll">全选</van-checkbox>
            <template #tip>
              你的收货地址不支持同城送,
              <span>修改地址</span>
            </template>
            <template #button>
              <div>
                <van-button round type="default" color="#bbb">移至收藏</van-button>
              <van-button round type="default" color="#bbb" @click="delAll">删除商品</van-button>
              </div>
            </template>
          </van-submit-bar>

          </div>
        </div>
      </div>

      <!-- 分割线 -->
      <van-divider
        :style="{
          color: '#999',
          borderColor: '#999',
          padding: '0 16px',
        }"
      >
        可能你还想要
      </van-divider>
      <!-- 推荐商品列表 -->
      <div class="top10">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <ul class="proList1">
            <li
              class="van-hairline--bottom van-hairline--right"
              v-for="item in proList"
              :key="item.proid"
              @click="jumpTo(item.proid)"
            >
              <img width="100%" :src="item.img1" alt="" />
              <div>
                <h4>{{ item.proname }}</h4>
                <p>￥{{ item.originprice.toFixed(2) }}</p>
                <span>销量{{ item.sales }}</span>
              </div>
              <b>看相似</b>
            </li>
          </ul>
        </van-list>
      </div>
      <!-- 回到顶部 -->
      <div class="top" v-if="scrollTop > 700" @click="backTop">
        <van-icon name="back-top" />
      </div>
    </main>
  </div>
</template>
 
<script>
import {
  dorecommendlist,
  getCartList,
  doUpdateNum,
  doCartRemove,
  doSelectone,
  doSelectAll,
  doRemoveAll,
  defaultAddress,
  addOrder
} from "../api/cart";
import Vue from "vue";
import {
  Divider,
  Empty,
  Card,
  SwipeCell,
  Stepper,
  Checkbox,
  CheckboxGroup,
  Toast,
  SubmitBar,
  Dialog
} from "vant";

Vue.use(Divider);
Vue.use(Empty);
Vue.use(Card);
Vue.use(SwipeCell);
Vue.use(Stepper);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Toast);
Vue.use(SubmitBar);
Vue.use(Dialog);
export default {
  name: "Cart",
  components: {},
  data() {
    return {
      showPopover: false,
      actions: [
        { text: "返回首页", icon: "wap-home-o" },
        { text: "分类搜索", icon: "apps-o" },
        { text: "购物车", icon: "shopping-cart-o" },
        { text: "我的京东", icon: "contact" },
        { text: "浏览记录", icon: "eye-o" },
      ],
      proList: [],
      loading: false,
      finished: false,
      count: 2,
      scrollTop: 0,
      empty: false,
      cartList: [],
      addressbtn:true,
      deAddress:'',
    };
  },
  methods: {
    getCartList(){
      getCartList({ userid: localStorage.getItem("userid") }).then((res) => {
      console.log(res.data.data);
      switch (res.data.code) {
        case "10020":
          this.empty = true;
          break;
        case "200":
          this.empty = false;
          this.cartList = res.data.data;
          break;
        default:
          break;
      }
      console.log(this.isAll);
    });
    },
    onSelect(action, index) {
      switch (index) {
        case 0:
          this.$router.push("/home");
          break;
        case 1:
          this.$router.push("/kind");
          break;
        case 2:
          this.$router.go(0);
          break;
        case 3:
          this.$router.push("/my");
          break;
        case 4:
          this.$router.push("/kind");
          break;
        default:
          break;
      }
    },
    onLoad() {
      (this.loading = true),
        setTimeout(() => {
          dorecommendlist({ count: this.count, limitNum: 12 }).then((res) => {
            this.loading = false;
            console.log(res.data.data);
            if (res.data.data.length == 0) {
              this.finished = true;
            } else {
              this.proList = [...this.proList, ...res.data.data];
              this.count++;
            }
          });
        }, 1000);
    },
    scrollMe() {
      this.scrollTop = this.$refs.main.scrollTop;
    },
    backTop() {
      const timer = setInterval(() => {
        if (this.$refs.main.scrollTop <= 0) {
          clearInterval(timer);
        }
        this.$refs.main.scrollTop -= 100;
      }, 15);
    },
    jumpTo(id) {
      this.$router.push("/detail/" + id);
    },
    changeNum(id, num) {
      //增加或者减少数量的接口
      doUpdateNum({ cartid: id, num: num }).then((res) => {
        console.log(res);
      });
    },
     // position 为关闭时点击的位置
    // instance 为对应的 SwipeCell 实例
    beforeClose({ name, position, instance}) {
      console.log( name, position, instance);
      switch (position) {
        case 'right':
          Dialog.confirm({
            message: '确定删除吗？',
          }).then(() => {
            doCartRemove({cartid:name}).then(res=>{
              console.log(res);
              if(res.data.code=="200"){
                Toast("删除成功")
                this.getCartList()
              }
            })
            instance.close();
          }).catch(()=>{
            instance.close();
          });
          break;
      }
    },
    changeSelector(id,flag){
      doSelectone({cartid:id,flag:flag}).then()
    },
    delAll(){
      doRemoveAll({userid:localStorage.getItem("userid")}).then(res=>{
        console.log(res);
        this.getCartList()
      })
    },
    onSubmit(){
      addOrder({userid:localStorage.getItem("userid")}).then(res=>{
        console.log(res.data.time);
        if(res.data.code==200){
          this.$router.push("/order/"+res.data.time)
        }
      })
    }
  },
  created() {
    if(localStorage.getItem("token")){
      this.getCartList()
      defaultAddress({userid:localStorage.getItem("userid")}).then(res=>{
        console.log(res);
        if(res.data.code==200){
          this.deAddress = ""+res.data.data[0].county+res.data.data[0].addressDetail
        }
      })
    }
    dorecommendlist({ count: 1, limitNum: 12 }).then((res) => {
      console.log(res.data.data);
      this.proList = res.data.data;
    });
  },
  computed: {
    loginState() {
      if (localStorage.getItem("token")) {
        return false;
      } else {
        return true;
      }
    }, 
  isAll:{
    get(){
      return this.cartList.every((item) => item.flag);
    },
    set(val){
      this.cartList.forEach(item => item.flag=val);
      doSelectAll({ userid:localStorage.getItem("userid"), type:val }).then()
    }
  },
  price(){
    const newList = this.cartList.filter(item=>item.flag)
    return newList.reduce((sum,item)=>sum+=(item.num*item.originprice)*100,0)
  },
  checkednum(){
    return this.cartList.filter(item=>item.flag).length
  }
  },
};
</script>

<style scoped>
.notlogin .vbtn {
  height: 0.3rem;
  width: 0.6rem;
  margin-left: 0.1rem;
}
main {
  background: rgb(240, 240, 240);
}
main .notlogin .cartlogin {
  background: #fff;
  height: 0.6rem;
  border-radius: 0 0 0.1rem 0.1rem;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 0.14rem;
}
.notlogin .carticon {
  text-align: center;
}
.notlogin .carticon div:nth-child(1) {
  height: 3rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.proList1 {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.proList1 li {
  width: 44%;
  height: 2.4rem;
  margin: 0.1rem 0.1rem;
  position: relative;
}
.proList1 li img {
  width: 80%;
  height: 50%;
  margin: 0.2rem;
  border-radius: 0.06rem;
}
.proList1 li h4 {
  width: 100%;
  font-size: 0.14rem;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.proList1 li p {
  color: rgb(201, 22, 35);
  bottom: 0.1rem;
}
.proList1 li span {
  color: #999;
  font-size: 0.14rem;
}
.proList1 li b {
  font-size: 0.1rem;
  position: absolute;
  right: 0.1rem;
  bottom: 0.01rem;
  background: rgb(225, 225, 225);
  width: 0.5rem;
  height: 0.2rem;
  border-radius: 0.1rem;
  text-align: center;
  line-height: 0.2rem;
}
.top {
  position: fixed;
  bottom: 0.3rem;
  right: 0.1rem;
  background: red;
  z-index: 9;
}
.top {
  position: fixed;
  bottom: 0.6rem;
  right: 0.1rem;
  display: inline-block;
  width: 0.24rem;
  height: 0.24rem;
  text-align: center;
  line-height: 0.24rem;
  color: #fff;
  border-radius: 50%;
}
.delete-button {
  height: 100%;
}
::v-deep .van-swipe-cell__wrapper {
  display: flex;
  background: #fff;
}
::v-deep .van-checkbox {
  width: 0.3rem;
  padding-left: 0.1rem;
}
::v-deep .van-card {
  flex: 1;
}
.adress{
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: .4rem;
  margin-bottom: .08rem;
  background: #fff;
  font-size: .14rem;
  padding: 0 .1rem;
  border-radius: 0 0 .1rem .1rem;
}
::v-deep .van-submit-bar__bar{
  display: flex;
  justify-content: space-between;
}
::v-deep .van-submit-bar{
  bottom: .44rem;
}
</style>